package com.hbu.product.hbumallproduct.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbu.common.TO.SkuReductionTO;
import com.hbu.common.TO.SpuBoundTO;
import com.hbu.common.TO.es.SkuEsModel;
import com.hbu.common.constant.ProductConstant;
import com.hbu.common.utils.PageUtils;
import com.hbu.common.utils.Query;
import com.hbu.product.hbumallproduct.dao.*;
import com.hbu.product.hbumallproduct.entity.*;
import com.hbu.product.hbumallproduct.feign.CouponFeignService;
import com.hbu.product.hbumallproduct.feign.SearchFeignService;
import com.hbu.product.hbumallproduct.feign.WareFeignService;
import com.hbu.product.hbumallproduct.service.*;
import com.hbu.product.hbumallproduct.vo.SpuInfoListVO;
import com.hbu.product.hbumallproduct.vo.spusave.Images;
import com.hbu.product.hbumallproduct.vo.spusave.Skus;
import com.hbu.product.hbumallproduct.vo.spusave.SpuSaveVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.hbu.common.utils.Constant.DEFAULT_URL_IMG_STATUS;


/**
 * @author 90458
 */
@Service("spuInfoService")
@AllArgsConstructor
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    private SpuInfoDescDao spuInfoDescDao;

    private SpuImagesService spuImagesService;

    private AttrDao attrDao;

    private ProductAttrValueService productAttrValueService;

    private SkuInfoDao skuInfoDao;

    private SkuImagesService skuImagesService;

    private SkuSaleAttrValueService skuSaleAttrValueService;

    private CouponFeignService couponFeignService;

    private BrandDao brandDao;

    private CategoryDao categoryDao;

    private WareFeignService wareFeignService;

    private SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getList(SpuInfoListVO spuInfoList) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = spuInfoList.getKey();
        if (StringUtils.hasText(key)) {
            queryWrapper.and(row -> row.eq("id", key).or().like("spu_name", key));
        }
        Long brandId = spuInfoList.getBrandId();
        if (null != brandId && brandId != 0) {
            queryWrapper.eq("brand_id", brandId);
        }
        Long catelogId = spuInfoList.getCatelogId();
        if (null != catelogId && catelogId != 0) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        Integer status = spuInfoList.getStatus();
        boolean statusFlag = null != status && (status.equals(0) || status.equals(1) || status.equals(2));
        if (statusFlag) {
            queryWrapper.eq("publish_status", status);
        }
        return new PageUtils(this.page(new Page<>(spuInfoList.getPageOrDefault(), spuInfoList.getLimitOrDefault()), queryWrapper));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void spuShelves(Long spuId) {
        List<SkuEsModel> esModelsList = skuInfoDao.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId)).stream().map(skuInfoEntity -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            skuEsModel.setSkuId(skuInfoEntity.getSkuId());
            skuEsModel.setSpuId(spuId);
            skuEsModel.setSkuTitle(skuInfoEntity.getSkuTitle());
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            skuEsModel.setSaleCount(skuInfoEntity.getSaleCount());
            skuEsModel.setHasStock(wareFeignService.getSkuStockStatus(skuInfoEntity.getSkuId()));
            // TODO: 2022/12/4 商品热度 Spark + HIVE
            skuEsModel.setHotScore(0L);
            skuEsModel.setBrandId(skuInfoEntity.getBrandId());
            BrandEntity brand = brandDao.selectOne(new QueryWrapper<BrandEntity>()
                    .eq("brand_id", skuInfoEntity.getBrandId()).select("name", "logo"));
            skuEsModel.setBrandName(brandDao.getNameById(skuInfoEntity.getBrandId()));
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());
            skuEsModel.setCatalogId(skuInfoEntity.getCatalogId());
            skuEsModel.setCatalogName(categoryDao.getNameById(skuInfoEntity.getCatalogId()));
            skuEsModel.setAttrs(skuSaleAttrValueService.getAttrList(skuInfoEntity.getSkuId()));
            return skuEsModel;
        }).collect(Collectors.toList());
        log.debug("最终要上架的商品信息为:");
        for (SkuEsModel skuEsModel : esModelsList) {
            log.debug(skuEsModel.toString());
        }
        searchFeignService.productShelves(esModelsList);
        baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.PRODUCT_UP.getCode());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuSaveVO(SpuSaveVO spuSaveVO) {

        log.debug("接受到的数据为" + spuSaveVO);

        // 1、保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtil.copyProperties(spuSaveVO, spuInfoEntity);
        baseMapper.insert(spuInfoEntity);

        Long spuId = spuInfoEntity.getId();

        // 2、保存spu的描述图片 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",", spuSaveVO.getDecript()));
        spuInfoDescDao.insert(spuInfoDescEntity);

        // 3、保存spu的图片集  pms_spu_images
        List<SpuImagesEntity> spuImageList = spuSaveVO.getImages().stream().map(image -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuId);
            spuImagesEntity.setImgUrl(image);
            return spuImagesEntity;
        }).collect(Collectors.toList());
        spuImagesService.saveBatch(spuImageList);

        // 4、保存spu的规格参数 pms_product_attr_value
        List<ProductAttrValueEntity> productAttrValueList = spuSaveVO.getBaseAttrs().stream().map(attr -> {
            ProductAttrValueEntity productAttrValue = new ProductAttrValueEntity();
            productAttrValue.setAttrId(attr.getAttrId());
            productAttrValue.setAttrValue(attr.getAttrValues());
            productAttrValue.setSpuId(spuId);
            productAttrValue.setQuickShow(attr.getShowDesc());
            productAttrValue.setAttrName(attrDao.getAttrName(attr.getAttrId()));
            return productAttrValue;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueList);
        // 5、保存spu的积分信息 hbumall_sms -> sms_spu_bounds
        SpuBoundTO spuBound = new SpuBoundTO();
        spuBound.setSpuId(spuId);
        BeanUtil.copyProperties(spuSaveVO.getBounds(), spuBound);
        couponFeignService.saveSpuBounds(spuBound);

        // 6、保存当前spu对应的所有sku信息
        List<Skus> skus = spuSaveVO.getSkus();
        if (null != skus && !skus.isEmpty()) {
            for (Skus sku : skus) {
                // 6.1、保存sku的基本信息    pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtil.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuId);
                for (Images image : sku.getImages()) {
                    if (DEFAULT_URL_IMG_STATUS.equals(image.getDefaultImg())) {
                        skuInfoEntity.setSkuDefaultImg(image.getImgUrl());
                        break;
                    }
                }
                skuInfoDao.insert(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                // 6.2、sku的图片信息       pms_sku_images
                List<SkuImagesEntity> skuImagesList = sku.getImages().stream()
                        .filter(images -> StringUtils.hasText(images.getImgUrl())).map(img -> {
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuId);
                            skuImagesEntity.setImgUrl(img.getImgUrl());
                            skuImagesEntity.setDefaultImg(img.getDefaultImg());
                            return skuImagesEntity;
                        }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesList);
                // 6.3、sku的销售属性信息    pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> skuSaleAttrValueList = sku.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValue = new SkuSaleAttrValueEntity();
                    BeanUtil.copyProperties(attr, skuSaleAttrValue);
                    skuSaleAttrValue.setSkuId(skuId);
                    return skuSaleAttrValue;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueList);

                // 6.4、sku的优惠、满减等信息 hbumall_sms-> sms_sku_ladder + sms_sku_full_reduction + sms_member_price
                SkuReductionTO skuReduction = new SkuReductionTO();
                BeanUtil.copyProperties(sku, skuReduction);
                skuReduction.setSkuId(skuId);
                couponFeignService.saveSkuReduction(skuReduction);
            }
        }

    }


}